<template>
<div class="user_add_or_update">
  <el-dialog :visible.sync="visible"
             :title="!dataForm.id ? $t('add') : $t('update')"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             >
    <el-form :model="dataForm"
             :rules="dataRule"

             ref="dataForm"
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="180px"
             v-loading="loading"
            >
      <el-tooltip class="item"
                  :open-delay="1000"
                  effect="dark"
                  disabled
                  :content="$t('user.tooltipcontent')"
                  placement="top">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('user.username')" prop="username">
              <el-input v-model="dataForm.username"
                        :disabled='false'
                        :placeholder="$t('user.username')"></el-input>
            </el-form-item>
            <el-form-item class='email'
                          :label="$t('user.email')">
              <el-input v-model="dataForm.email"
                        :disabled='false'
                        :placeholder="$t('user.email')"></el-input>
            </el-form-item>
            <!-- <el-form-item :label="$t('user.firstName')">
              <el-input v-model="dataForm.firstName"
                        :disabled='false'
                        :placeholder="$t('user.firstName')"></el-input>
            </el-form-item> -->
            <!-- <el-form-item :label="$t('user.lastName')">
              <el-input v-model="dataForm.lastName"
                        :disabled='false'
                        :placeholder="$t('user.lastName')"></el-input>
            </el-form-item> -->
            <el-form-item :label="$t('user.displayName')">
              <el-input v-model="dataForm.realName"
                        :disabled='false'
                        :placeholder="$t('user.displayName')"></el-input>
            </el-form-item>
            <el-form-item :label="$t('user.mobile')">
              <el-input v-model="dataForm.mobile"
                        :disabled='false'
                        :placeholder="$t('user.mobile')"></el-input>
            </el-form-item>
            <!-- <el-form-item :label="$t('user.managerName')">
              <el-select v-model="dataForm.managerId"
                         :disabled='false'
                         style="width:100%;"
                         filterable
                         clearable
                         default-first-option
                         :placeholder="$t('user.managerName')">
                <el-option v-for="user in managerList"
                           :key="user.id"
                           :label="user.username + ' (' + user.email + ')'"
                           :value="user.id">
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item :label="$t('user.deptName')"
                          v-if="false">
              <ren-dept-tree v-model="dataForm.deptId"
                             :placeholder="$t('dept.title')"
                             :dept-name.sync="dataForm.deptName"></ren-dept-tree>
            </el-form-item><br>
            <!-- <el-form-item :label="$t('user.password')" prop="password">
              <el-input v-model="dataForm.password"
                        :disabled='false'
                        :placeholder="$t('user.password')"></el-input>
            </el-form-item>
            <el-form-item :label="$t('user.confirmPassword')" prop="confirmPassword">
              <el-input v-model="dataForm.confirmPassword"
                        :disabled='false'
                        :placeholder="$t('user.confirmPassword')"></el-input>
            </el-form-item> -->
          </el-col>
        </el-row>
      </el-tooltip>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="status"
                        :label="$t('user.status')"
                        size="mini">
            <el-radio-group v-model="dataForm.status" @change="statusChange">
              <el-radio :disabled="isMe" :label="0">{{ dataForm.status ? $t('user.status0') : $t('user.status00') }}</el-radio>
              <el-radio :disabled="isMe" :label="1">{{ dataForm.status ? $t('user.status11') : $t('user.status1') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item prop="teamsMessageSwitch"
                        :label="$t('user.teamsMessageSwitch')">
            <el-switch :disabled='disabledUser'
                       v-model="dataForm.teamsMessageSwitch">
            </el-switch>
          </el-form-item> -->
          <el-form-item prop="roleIdList"
                        :label="$t('user.roleIdList')">
            <el-select v-model="dataForm.roleIdList"
                       multiple
                       collapse-tags                       
                       :placeholder="$t('user.roleIdList')">
              <el-option v-for="(role,index) in fullRoleList"
                         :key="index"
                         :label="role.name"
                         :value="role.roleId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="connectorSetting['CW']"
                        prop="cwUserMapping"
                        :label="$t('user.cwUserMapping')">
            <el-select v-model="dataForm.cwUid"
                       style="width:100%;"
                       filterable
                       :disabled='disabledUser'
                       default-first-option
                       :placeholder="$t('user.cwUserMapping')">
              <el-option v-for="item in mappingLists.cwUserList"
                         :key="item.cwUid"
                         :label="item.email"
                         :value="item.cwUid">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="connectorSetting['TEAMS']"
                        prop="teamsUserMapping"
                        :label="$t('user.teamsUserMapping')">
            <el-select v-model="dataForm.teamsUserId"
                       style="width:100%;"
                       filterable
                       :disabled='disabledUser'
                       default-first-option
                       :placeholder="$t('user.teamsUserMapping')">
              <el-option v-for="item in mappingLists.teamsUserList"
                         :key="item.teamsUserId"
                         :label="item.teamsMail"
                         :value="item.teamsUserId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="connectorSetting['TSHEET']"
                        prop="sheetsUserMaapping"
                        :label="$t('user.sheetsUserMaapping')">
            <el-select v-model="dataForm.sheetUserId"
                       style="width:100%;"
                       filterable
                       :disabled='disabledUser'
                       default-first-option
                       :placeholder="$t('user.sheetsUserMaapping')">
              <el-option v-for="item in mappingLists.sheetsUserList"
                         :key="item.sheetUserId"
                         :label="item.email"
                         :value="item.sheetUserId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="connectorSetting['TD']"
                        prop="timeDoctorUserMapping"
                        :label="$t('user.timeDoctorUserMapping')">
            <el-select v-model="dataForm.timedoctorUser"
                       style="width:100%;"
                       filterable
                       :disabled='disabledUser'
                       default-first-option
                       :placeholder="$t('user.timeDoctorUserMapping')">
              <el-option v-for="item in mappingLists.timedoctorUserList"
                         :key="item.userId"
                         :label="item.email"
                         :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="connectorSetting['AUTOTASK']"
                        prop="autotaskUserMapping"
                        :label="$t('user.autotaskUserMapping')">
            <el-select v-model="dataForm.autotaskUser"
                       style="width:100%;"
                       filterable
                       :disabled='disabledUser'
                       default-first-option
                       :placeholder="$t('user.autotaskUserMapping')">
              <el-option v-for="item in mappingLists.autotaskUserList"
                         :key="item.userId"
                         :label="item.email"
                         :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item :label="$t('user.homeChannel')"> -->
            <!-- <el-select v-model="dataForm.homeChannel"
                       style="width:100%;"
                       filterable
                       default-first-option
                       :placeholder="$t('user.homeChannel')">
              <el-option v-for="item in dataForm.teamsChannelList"
                         :key="item.channelId"
                         :label="item.displayName"
                         :value="item.channelId">
              </el-option>
            </el-select>  -->
            <!-- <div style="position:relative;">
              <el-input
                        v-model="homeChannelinput"
                        @input="channelInput"
                        @focus='channelFocus'
                        @blur='channelBlur'
                        ref="channel-input"
                        clearable
                        :placeholder="$t('user.homeChannel')"></el-input>
              <div class="custom-collapse-css card-css scroll-css"
                   v-if="setChannelStatus"
                   @click="clickChannelCard">
                <el-collapse accordion v-model="activeNames">
                  <el-collapse-item v-for="(value,key) in teamsChannelList"
                                    :key="key"
                                    :name="key">
                    <template slot="title">
                      {{ key }}
                    </template>
                    <template v-for="(it,j) in value">
                      <div :key="j">
                        <el-radio v-model="dataForm.homeChannel"
                                  :label="it.channelId">{{ it.displayName }}</el-radio>
                      </div>
                    </template>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </el-form-item> -->
        </el-col>
      </el-row>

    </el-form>
    <template slot="footer">
      <el-button @click="visible = false"
                 size="small">{{ $t('cancel') }}</el-button>
      <el-button type="primary"
                 size="small"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
  <el-dialog
      :title="$t('custom.apps.warning')"
      :visible.sync="dialogVisible"
      width="30%">
      <span style="font-size: 14px;color: #404040;line-height: 22px;">{{$t('user.warning')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="dialogVisible = false,dataForm.status = 1">{{$t('cancel')}}</el-button>
        <el-button type="primary" size="mini" @click="dialogVisible = false">{{$t('user.disable')}}</el-button>
        <el-button type="primary" size="mini" :disabled="!$hasPermission('sys:user:update')" @click="dialogVisible = false,dataForm.status = 1,dataForm.teamsMessageSwitch = false">{{$t('user.Turnusersmessageswitch')}}</el-button>
      </span>
    </el-dialog>
</div>
</template>

<script>
import { debounce } from 'lodash'
import qs from 'qs'
// import { isMobile } from '@/utils/validate'// isEmail
export default {
  props: {
    connectorSetting: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      dialogVisible: false,
      homeChannelinput: '',
      activeNames: [],
      visible: false,
      roleList: [],
      managerList: [],
      roleIdListDefault: [],
      loading: false,
      dataForm: {
        id: '',
        username: '',
        firstName: '',
        lastName: '',
        deptId: '',
        deptName: '',
        password: '123456',
        confirmPassword: '123456',
        realName: '',
        gender: 0,
        email: '',
        mobile: '',
        roleIdList: [],
        status: 1,
        managerId: '',
        cwUid: '',
        teamsUserId: '',
        sheetUserId: '',
        timedoctorUser: '',
        autotaskUser: '',
        teamsMessageSwitch: true,
        homeChannel: ''
      },
      mappingLists: {
        cwUserList: [],
        teamsUserList: [],
        sheetsUserList: [],
        timedoctorUserList: [],
        autotaskUserList: []
      },
      tempMappingList: [
        { userId: null, userType: '1', mappingUserId: null, tenantCode: this.$store.state.user.tenantCode, id: null },
        { userId: null, userType: '2', mappingUserId: null, tenantCode: this.$store.state.user.tenantCode, id: null },
        { userId: null, userType: '3', mappingUserId: null, tenantCode: this.$store.state.user.tenantCode, id: null },
        { userId: null, userType: '4', mappingUserId: null, tenantCode: this.$store.state.user.tenantCode, id: null }
      ],
      disabledUser: false,
      setChannelStatus: false,
      tempCardHas: false,
      teamsChannelList: []
    }
  },
  computed: {
    dataRule () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t('validate.required')))
        }
        callback()
      }
      var validateConfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t('validate.required')))
        }
        if (this.dataForm.password !== value) {
          return callback(new Error(this.$t('user.validate.confirmPassword')))
        }
        callback()
      }
      return {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        firstName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        lastName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ],
        realName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        email: [
          //  { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          // { validator: validateMobile, trigger: 'blur' }
        ],
        cwUid: [],
        teamsUserId: [],
        sheetUserId: [],
        timedoctorUser: [],
        autotaskUser: []
      }
    },
    isMe (val) {
      if (this.dataForm.id === this.$store.state.user.id) {
        return true
      }
      if (!this.$hasPermission('sys:user:assignrole')) {
        return true
      }
    },
    dataFormHomeChannel () {
      return this.dataForm.homeChannel
    },
    fullRoleList () {
      let roleList = this.roleList
      let roleTemp = []
      let assignTemp = []
      let temp = []
      roleList.forEach(ii => {
        roleTemp.push({
          roleId: ii.roleId,
          name: ii.name
        })
      })
      // temp code: because tenant not create role  issue
      //  assignTemp = []
      if (assignTemp.length > 0) {
        temp = this._.intersectionBy(roleTemp, assignTemp, 'roleId')
      } else {
        temp = roleTemp
      }
      return temp
    }
  },
  mounted () {
    // custom-collapse-css
  },
  destroyed () { },
  watch: {
    visible (val) {
      if (!val) {
        this.dataForm = {
          id: '',
          username: '',
          firstName: '',
          lastName: '',
          deptId: '',
          deptName: '',
          password: '123456',
          confirmPassword: '123456',
          realName: '',
          gender: 0,
          email: '',
          mobile: '',
          roleIdList: [],
          status: 1,
          managerId: '',
          cwUid: '',
          teamsUserId: '',
          sheetUserId: '',
          timedoctorUser: '',
          autotaskUser: '',
          teamsMessageSwitch: true,
          homeChannel: ''
        }
      }
    },
    dataFormHomeChannel (val) {
      this.homeChannelinput = this.homeChannelLabel()
      this.teamsChannelList = this.dataForm.teamsChannelList
    }
  },
  methods: {
    statusChange (val) {
      if (!val) {
        if (!this.dataForm.isGuestUser && (this.dataForm.cwUserName || this.dataForm.autoTaskUserName)) {
          this.dialogVisible = true
        }
      }
    },
    homeChannelLabel () {
      try {
        let tempList = []
        for (const key in this.dataForm.teamsChannelList) {
          tempList = [...tempList, ...this.dataForm.teamsChannelList[key]]
        }
        return tempList.find(e => e.channelId === this.dataForm.homeChannel).groupName + '/' + tempList.find(e => e.channelId === this.dataForm.homeChannel).displayName
      } catch (err) {
        return null
      }
    },
    channelFocus () {
      this.setChannelStatus = true
    },
    channelInput: debounce(function (str) {
      this.activeNames = []
      let channelList = {}
      if (str) {
        for (const key in this.dataForm.teamsChannelList) {
          if (Object.hasOwnProperty.call(this.dataForm.teamsChannelList, key)) {
            const element = this.dataForm.teamsChannelList[key]
            if (key.toLowerCase().indexOf(str.toLowerCase()) !== -1) {
              channelList[key] = element
            }
            element.forEach(ele => {
              if (ele.displayName.toLowerCase().indexOf(str.toLowerCase()) !== -1) {
                if (channelList.hasOwnProperty(key)) {
                  channelList[key].push(ele)
                } else {
                  this.activeNames.push(key)
                  channelList[key] = []
                  channelList[key].push(ele)
                }
              }
            })
          }
        }
        this.teamsChannelList = channelList
      } else {
        this.homeChannelinput = ''
        this.dataForm.homeChannel = null
        this.activeNames = []
        this.teamsChannelList = this.dataForm.teamsChannelList
      }
    }, 800),
    channelBlur () {
      setTimeout(() => {
        if (!this.tempCardHas) {
          this.setChannelStatus = false
        }
      }, 300)
    },
    clickChannelCard (e) {
      if (e.target.tagName === 'DIV') {
        this.tempCardHas = true
        this.$refs['channel-input'].focus()
        setTimeout(() => {
          this.tempCardHas = false
        }, 300)
      }
    },
    init () {
      this.visible = true
      this.dataForm.deptId = ''
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.roleIdListDefault = []
        this.getRoleList()
        this.getMappingList()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    getRoleList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      return this.$interface.system.getClientRoleListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.roleList = res.data
        }).catch(() => { })
    },

    getInfo () {
      this.loading = true
      this.$interface.system.getUserInfoWithIdApi(this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm.roleIdList = []
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
            roleIdList: []
          }
          this.dataForm.confirmPassword = this.dataForm.password
          delete this.dataForm.confirmPassword
          delete this.dataForm.password
          this.teamsChannelList = this.dataForm.teamsChannelList
          this.getManager()
          for (var i = 0; i < res.data.roleIdList.length; i++) {
            if (this.fullRoleList.filter(item => item.roleId === res.data.roleIdList[i])[0]) {
              this.dataForm.roleIdList.push(res.data.roleIdList[i])
              continue
            }
            this.roleIdListDefault.push(res.data.roleIdList[i])
          }
          this.disabledUser = false
          if (res.data.status === 0) {
            this.disabledUser = true
          }
          let tempList = res.data.mappingList
          tempList && tempList.length && (tempList.length > 0) && (this.tempMappingList = tempList)
          tempList.find(e => e.userType === '1') ? (this.dataForm.teamsUserId = tempList.find(e => e.userType === '1').mappingUserId) : (this.dataForm.teamsUserId = null)
          tempList.find(e => e.userType === '2') ? (this.dataForm.cwUid = tempList.find(e => e.userType === '2').mappingUserId) : (this.dataForm.cwUid = null)
          tempList.find(e => e.userType === '3') ? (this.dataForm.sheetUserId = tempList.find(e => e.userType === '3').mappingUserId) : (this.dataForm.sheetUserId = null)
          tempList.find(e => e.userType === '4') ? (this.dataForm.timedoctorUser = tempList.find(e => e.userType === '4').mappingUserId) : (this.dataForm.timedoctorUser = null)
          tempList.find(e => e.userType === '5') ? (this.dataForm.autotaskUser = tempList.find(e => e.userType === '5').mappingUserId) : (this.dataForm.autotaskUser = null)
          // autotaskUser
          this.loading = false
        }).catch(() => { })
    },
    getManager () {
      this.$interface.system.getUserManagerListApi({ id: this.dataForm.id, tenantCode: this.dataForm.tenantCode })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.managerList = res.data
        }).catch(() => { })
    },
    getMappingList () {
      const params = {}
      this.dataForm.id && (params.userId = this.dataForm.id)
      this.$interface.taskManager.getUserMappingListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.mappingLists = res.data
        }).catch(() => { })
    },
    arrayUpdateWay (arr, nexArr) {
      nexArr && nexArr.length && nexArr.map(e => {
        arr.push(e)
      })
    },
    buildMapping () {
      let mappingList = []
      let arr = ['1', '2', '3', '4', '5']
      arr.forEach(userType => {
        let mappingUserId = null
        switch (userType) {
          case '1':
            mappingUserId = this.dataForm.teamsUserId
            break
          case '2':
            mappingUserId = this.dataForm.cwUid
            break
          case '3':
            mappingUserId = this.dataForm.sheetUserId
            break
          case '4':
            mappingUserId = this.dataForm.timedoctorUser
            break
          case '5':
            mappingUserId = this.dataForm.autotaskUser
        }
        if (mappingUserId) {
          let mapping = this.tempMappingList.find(item => item.userType === userType)
          if (mapping != null) {
            mapping.mappingUserId = mappingUserId
          } else {
            mapping = { userId: this.dataForm.id, userType: userType, mappingUserId: mappingUserId, tenantCode: this.dataForm.tenantCode }
          }
          mappingList.push(mapping)
        }
      })
      return mappingList
    },
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        let mappingListData = this.buildMapping()
        const params = {
          ...this.dataForm,
          roleIdList: [
            ...this.dataForm.roleIdList,
            ...this.roleIdListDefault
          ],
          mappingList: mappingListData
        }
        if(params.roleIdList.length === 0){
          return this.$message.error('至少选择一个角色')
        }
        const changeSysUser = () => {
          if (!this.dataForm.id) {
            params.regSource = 2
            return this.$interface.system.postSysUser(params)
          } else {
            return this.$interface.system.putSysUser(params)
          }
        }
        changeSysUser().then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}

.role-list {
  width: 100%;
}

.role-list .el-form-item__content,
.email .el-form-item__content,
.deptname .el-form-item__content {
  min-width: 110px;
}

.role-list .el-form-item__content .el-select {
  width: 100%;
}
.custom-collapse-css {
  .el-collapse-item__header {
    height: 30px;
    line-height: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    border-bottom: none;
  }
  .el-collapse-item__content {
    padding-bottom: 0;
  }
  .el-collapse-item__wrap {
    border-bottom: none;
  }
  .el-radio__inner {
    width: 10px;
    height: 10px;
  }
  .el-radio {
    color: #666666;
  }
  .el-radio__label {
    font-size: 13px;
  }
}
</style>
<style lang="scss">
.user_add_or_update{
  .card-css {
    position: absolute;
    width: 100%;
    max-height: 250px;
    padding: 12px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;
    color: #303133;
    -webkit-transition: 0.3s;
    transition: 0.3s;
    margin-bottom: 30px;
  }
  .el-form-item__label {
    padding: 0 13px 0 0;
  }
  ::v-deep .el-dialog__body{
    overflow: inherit;
  }
}

</style>
<style scoped>
::v-deep .el-form-item{
      margin-bottom: 22px;
    }
</style>
